
/*
 * FichaKine.java
 *
 * Created on 16-10-2012, 02:57:22 PM
 */
package SubsistemaPaciente.Fichas;

import clienteSandraParada.Login;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jacqueline
 */
public class FichaKine extends javax.swing.JDialog {

    Long id;
    int fila;
    String profesional = Login.getUser().getRut();
    private PanelKine p;

    /** Creates new form FichaKine */
    public FichaKine(java.awt.Frame parent, boolean modal, PanelKine p) {
        super(parent, modal);
        initComponents();
        this.p = p;
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel16 = new javax.swing.JPanel();
        botonAgregar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        jPanel17 = new javax.swing.JPanel();
        jLabel42 = new javax.swing.JLabel();
        jLabel43 = new javax.swing.JLabel();
        jLabel44 = new javax.swing.JLabel();
        nombres1 = new javax.swing.JTextField();
        apellidoPaterno1 = new javax.swing.JTextField();
        jLabel45 = new javax.swing.JLabel();
        rut = new componentes.Rut();
        apellidoMaterno1 = new javax.swing.JTextField();
        jLabel46 = new javax.swing.JLabel();
        prevision = new javax.swing.JTextField();
        jLabel47 = new javax.swing.JLabel();
        telefono = new componentes.Telefono();
        jPanel18 = new javax.swing.JPanel();
        jLabel48 = new javax.swing.JLabel();
        jLabel49 = new javax.swing.JLabel();
        jLabel50 = new javax.swing.JLabel();
        jLabel51 = new javax.swing.JLabel();
        jLabel52 = new javax.swing.JLabel();
        jLabel53 = new javax.swing.JLabel();
        examenes1 = new javax.swing.JTextField();
        diagnostico1 = new javax.swing.JTextField();
        patologias1 = new javax.swing.JTextField();
        tratamiento1 = new javax.swing.JTextField();
        fechaIngreso1 = new com.toedter.calendar.JDateChooser();
        cancelacion1 = new com.toedter.calendar.JDateChooser();
        jLabel54 = new javax.swing.JLabel();
        jScrollPane8 = new javax.swing.JScrollPane();
        evaluacion1 = new javax.swing.JTextArea();
        jLabel20 = new javax.swing.JLabel();
        jScrollPane9 = new javax.swing.JScrollPane();
        evaluacionFinal1 = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jPanel19 = new javax.swing.JPanel();
        jScrollPane10 = new javax.swing.JScrollPane();
        tablaPrograma1 = new javax.swing.JTable();
        agregarPrograma1 = new javax.swing.JButton();
        modificarPrograma1 = new javax.swing.JButton();
        desdePro1 = new com.toedter.calendar.JDateChooser();
        jLabel21 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        hastaPro1 = new com.toedter.calendar.JDateChooser();
        verEvolucion = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        mensajeriaFormulario = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(1115, 700));

        botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        botonAgregar.setText("Guardar");
        botonAgregar.setToolTipText("Guardar");
        botonAgregar.setAlignmentY(0.0F);
        botonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAgregarActionPerformed(evt);
            }
        });

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.setToolTipText("Eliminar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        jPanel17.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos personales"));

        jLabel42.setText("Rut:");

        jLabel43.setText("Nombres:");

        jLabel44.setText("Apellido paterno:");

        nombres1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nombres1ActionPerformed(evt);
            }
        });

        jLabel45.setText("Apellido materno:");

        jLabel46.setText("Previsión");

        jLabel47.setText("Telefono:");

        javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
        jPanel17.setLayout(jPanel17Layout);
        jPanel17Layout.setHorizontalGroup(
            jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel17Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel44)
                    .addComponent(jLabel43)
                    .addComponent(jLabel42)
                    .addComponent(jLabel45)
                    .addComponent(jLabel46))
                .addGap(12, 12, 12)
                .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nombres1, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rut, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel17Layout.createSequentialGroup()
                        .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel17Layout.createSequentialGroup()
                                .addComponent(prevision, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel47))
                            .addComponent(apellidoMaterno1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                            .addComponent(apellidoPaterno1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(81, 81, 81))
        );
        jPanel17Layout.setVerticalGroup(
            jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel17Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel42)
                    .addComponent(rut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel43)
                    .addComponent(nombres1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel17Layout.createSequentialGroup()
                        .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel44)
                            .addComponent(apellidoPaterno1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel45)
                            .addComponent(apellidoMaterno1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel46)
                            .addComponent(prevision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel47)))
                    .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jPanel18.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos clínicos"));

        jLabel48.setText("Diagnóstico:");

        jLabel49.setText("Patologías:");

        jLabel50.setText("Tratamiento:");

        jLabel51.setText("Fecha ingreso:");

        jLabel52.setText("Cancelación:");

        jLabel53.setText("Exámenes");

        jLabel54.setText("Evaluación inicial:");

        evaluacion1.setColumns(20);
        evaluacion1.setRows(5);
        jScrollPane8.setViewportView(evaluacion1);

        jLabel20.setText("Evaluación final:");

        evaluacionFinal1.setColumns(20);
        evaluacionFinal1.setRows(5);
        jScrollPane9.setViewportView(evaluacionFinal1);

        jLabel6.setText("*");

        jLabel9.setText("*");

        jLabel10.setText("*");

        javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
        jPanel18.setLayout(jPanel18Layout);
        jPanel18Layout.setHorizontalGroup(
            jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel18Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel18Layout.createSequentialGroup()
                        .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel48)
                            .addComponent(jLabel53)
                            .addComponent(jLabel49)
                            .addComponent(jLabel50)
                            .addComponent(jLabel51)
                            .addComponent(jLabel52)
                            .addComponent(jLabel54))
                        .addGap(12, 12, 12)
                        .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel18Layout.createSequentialGroup()
                                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(fechaIngreso1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                                    .addComponent(cancelacion1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel18Layout.createSequentialGroup()
                                .addComponent(tratamiento1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel9))
                            .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel18Layout.createSequentialGroup()
                                    .addComponent(diagnostico1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel6))
                                .addComponent(examenes1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE)
                                .addComponent(patologias1, javax.swing.GroupLayout.Alignment.LEADING))))
                    .addGroup(jPanel18Layout.createSequentialGroup()
                        .addComponent(jLabel20)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel18Layout.setVerticalGroup(
            jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel18Layout.createSequentialGroup()
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(diagnostico1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel48)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(examenes1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel53))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(patologias1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel49))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tratamiento1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel50)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel51)
                    .addComponent(fechaIngreso1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel52, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cancelacion1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel54))
                .addGap(21, 21, 21)
                .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel20))
                .addContainerGap(75, Short.MAX_VALUE))
        );

        jPanel19.setBorder(javax.swing.BorderFactory.createTitledBorder("Atenciones realizadas"));

        tablaPrograma1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Sesión", "Fecha", "Evolución"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane10.setViewportView(tablaPrograma1);

        agregarPrograma1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png"))); // NOI18N
        agregarPrograma1.setToolTipText("Agregar evolución");
        agregarPrograma1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarPrograma1ActionPerformed(evt);
            }
        });

        modificarPrograma1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Edit2.png"))); // NOI18N
        modificarPrograma1.setToolTipText("Modificar evolución");
        modificarPrograma1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarPrograma1ActionPerformed(evt);
            }
        });

        desdePro1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                desdePro1PropertyChange(evt);
            }
        });

        jLabel21.setText("Desde:");

        jLabel22.setText("Hasta:");

        hastaPro1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                hastaPro1PropertyChange(evt);
            }
        });

        verEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Previsualizar.png"))); // NOI18N
        verEvolucion.setToolTipText("Ver evolución");
        verEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                verEvolucionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
        jPanel19.setLayout(jPanel19Layout);
        jPanel19Layout.setHorizontalGroup(
            jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel19Layout.createSequentialGroup()
                        .addComponent(jLabel21)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(desdePro1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel22)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hastaPro1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(modificarPrograma1, 0, 0, Short.MAX_VALUE)
                        .addComponent(agregarPrograma1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(verEvolucion, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel19Layout.setVerticalGroup(
            jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel19Layout.createSequentialGroup()
                .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel19Layout.createSequentialGroup()
                        .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel21)
                            .addComponent(jLabel22)
                            .addComponent(desdePro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(hastaPro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE))
                    .addGroup(jPanel19Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(agregarPrograma1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(modificarPrograma1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(verEvolucion)
                        .addGap(0, 400, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jLabel12.setText("* Datos obligatorios");

        javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
        jPanel16.setLayout(jPanel16Layout);
        jPanel16Layout.setHorizontalGroup(
            jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel16Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel18, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 756, Short.MAX_VALUE)
                        .addComponent(botonAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botonCancelar)))
                .addGap(58, 58, 58))
        );
        jPanel16Layout.setVerticalGroup(
            jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel16Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(botonCancelar)
                            .addComponent(botonAgregar))))
                .addContainerGap())
        );

        mensajeriaFormulario.setText("Área de mensajería");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(353, 353, 353)
                .addComponent(mensajeriaFormulario, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(535, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 6, Short.MAX_VALUE)
                    .addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 6, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(609, Short.MAX_VALUE)
                .addComponent(mensajeriaFormulario, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 4, Short.MAX_VALUE)
                    .addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 5, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarActionPerformed
        // TODO add your handling code here:
        boolean duplicada = false;
        if (this.getTitle().equals("Agregar Ficha Clinica")) {
            duplicada = estaDuplicada(rut.getRut().getText(), Login.getUser().getRut());
            boolean datosObligatorios = llenoDatosObligatorios();
            if (duplicada == false && datosObligatorios == true) {
                Long idFicha = p.agregarFichaClinicaBD(rut.getRut().getText(), profesional, diagnostico1.getText(), examenes1.getText(),
                        patologias1.getText(), evaluacion1.getText(), capturarFecha("cancelacion"),
                        tratamiento1.getText(), capturarFecha("fechaIngreso"), true, this.evaluacionFinal1.getText());
                service.FichaClinica f = buscarFicha(idFicha);
                String valorNuevo = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Anamnesis inmediata: " + f.getFechaIngreso() + "\n" + "Antecedentes familiares: " + f.getCancelacion() + "\n" + "CC: "
                        + f.getDiagnostico() + "\n" + "Desarrollo sicomotor: " + f.getEvaluacionInicial() + "\n" + "Eg: " + f.getEvaluacionFinal() + "\n" + "Hospitalizaciones: " + f.getExamenes() + "\n" + "Nombre madre: " + f.getPatologia() + "\n" + "Nombre padre: " + f.getTratamiento();
                registrar(Login.getUser(), "Ficha kinesiología", "Agregó ficha kinesiología a profesional:" + f.getProfesional() + "de paciente :" + f.getPaciente(), "No aplica", valorNuevo);
                p.cargarFichas((java.util.List<service.FichaClinica>) listarFichas());
            } else if (duplicada == true) {
                this.mensajeriaFormulario.setText("La ficha ya se encuentra en el sistema");
                this.mensajeriaFormulario.setForeground(Color.red);
            } else if (datosObligatorios == false) {
                this.mensajeriaFormulario.setText("Complete los campos obligatorios");
                this.mensajeriaFormulario.setForeground(Color.red);
            }
            if (duplicada == false && datosObligatorios == true) {
                this.dispose();
            }
        }
        if (this.getTitle().equals("Modificar Ficha Clinica")) {
            this.dispose();
            service.FichaClinica f = buscarFicha(id);
            String valorAnterior = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Anamnesis inmediata: " + f.getFechaIngreso() + "\n" + "Antecedentes familiares: " + f.getCancelacion() + "\n" + "CC: "
                    + f.getDiagnostico() + "\n" + "Desarrollo sicomotor: " + f.getEvaluacionInicial() + "\n" + "Eg: " + f.getEvaluacionFinal() + "\n" + "Hospitalizaciones: " + f.getExamenes() + "\n" + "Nombre madre: " + f.getPatologia() + "\n" + "Nombre padre: " + f.getTratamiento();
            p.modificarFichaClinicaBD(id, rut.getRut().getText(), profesional,
                    diagnostico1.getText(), examenes1.getText(), patologias1.getText(), evaluacion1.getText(),
                    capturarFecha("cancelacion"), tratamiento1.getText(), capturarFecha("fechaIngreso"), true,
                    this.evaluacionFinal1.getText());
            f = buscarFicha(id);
            //Cargar Fichas Kinesiologia
            p.cargarFichas((java.util.List<service.FichaClinica>) listarFichas());
            String valorNuevo = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Anamnesis inmediata: " + f.getFechaIngreso() + "\n" + "Antecedentes familiares: " + f.getCancelacion() + "\n" + "CC: "
                    + f.getDiagnostico() + "\n" + "Desarrollo sicomotor: " + f.getEvaluacionInicial() + "\n" + "Eg: " + f.getEvaluacionFinal() + "\n" + "Hospitalizaciones: " + f.getExamenes() + "\n" + "Nombre madre: " + f.getPatologia() + "\n" + "Nombre padre: " + f.getTratamiento();
            registrar(Login.getUser(), "Ficha kinesiología", "Modificó ficha kinesiología a profesional:" + f.getProfesional() + "de paciente :" + f.getPaciente(), valorAnterior, valorNuevo);
            p.cambiarMensajeria("La Ficha se ha modificado exitosamente");
        } else if (this.getTitle().equals("Ver Ficha Clinica")) {//Imprime la ficha Clinica
            try {
                //Imprime la ficha Clinica
                this.dispose();
                service.FichaClinica fichak = this.buscarFicha(id);
                imprimirFichaClinica(fichak);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(FichaKine.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(FichaKine.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_botonAgregarActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void nombres1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombres1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nombres1ActionPerformed

    private void desdePro1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_desdePro1PropertyChange
        // TODO add your handling code here:
        if (this.desdePro1.getDate() != null && this.hastaPro1.getDate() != null) {
            this.actualizarTablaFiltro();
        }
    }//GEN-LAST:event_desdePro1PropertyChange

    private void hastaPro1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_hastaPro1PropertyChange
        // TODO add your handling code here:
        if (this.desdePro1.getDate() != null && this.hastaPro1.getDate() != null) {
            this.actualizarTablaFiltro();
        }
    }//GEN-LAST:event_hastaPro1PropertyChange

    private void agregarPrograma1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarPrograma1ActionPerformed
        // agregar evolucion
        EvolucionKine evo = new EvolucionKine(null, true, this);
        evo.setTitle("Agregar Evolucion");
        evo.configurarBotones("agregar");
        evo.limpiarFormularioEvolucion();
        int sesion = calcularNumeroSesion(EvolucionKine.ficha);
        evo.agregarDatos(Integer.toString(sesion));
        evo.setLocationRelativeTo(null);
        evo.setVisible(true);
    }//GEN-LAST:event_agregarPrograma1ActionPerformed

    public int calcularNumeroSesion(Long ficha) {
        int numeroSesiones = 0;

        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();

        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        //buscar la ficha clinica por el id de la ficha
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).getFichaClinica().equals(ficha)) {
                numeroSesiones++;
            }
        }
        if (numeroSesiones == 0) {
            return 1;
        } else {
            return numeroSesiones + 1;
        }
    }

    private void modificarPrograma1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarPrograma1ActionPerformed
        // modificar Evolucion
        EvolucionKine evo = new EvolucionKine(null, true, this);
        evo.setTitle("Modificar Evolucion");
        evo.configurarBotones("modificar");
        int[] filasSelec = tablaPrograma1.getSelectedRows();
        if (filasSelec.length == 1) { //ha seleccionado una fila de la tabla
            int fil = filasSelec[0];
            service.Evolucion evoAModificar = buscarEvolucionAModificar((Integer) tablaPrograma1.getValueAt(fil, 0),
                    (String) tablaPrograma1.getValueAt(fil, 1), (String) tablaPrograma1.getValueAt(fil, 2));
            EvolucionKine.idEvolucion = evoAModificar.getId();
            EvolucionKine.idFichaEvo = evoAModificar.getFichaClinica();
            evo.llenarDatosFormularioEvolucion(evoAModificar);
            evo.habilitarCamposFormulario(true);
            evo.ocultarCamposObligatorios(false);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.mensajeriaFormulario.setText("Debe seleccionar una evolución");
            this.mensajeriaFormulario.setForeground(Color.red);
        }
    }//GEN-LAST:event_modificarPrograma1ActionPerformed

    private void verEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_verEvolucionActionPerformed
        // ver evolucion.
        EvolucionKine evo = new EvolucionKine(null, true, this);
        evo.setTitle("Ver Evolucion");
        evo.configurarBotones("ver");
        int[] filasSelec = tablaPrograma1.getSelectedRows();
        if (filasSelec.length == 1) { //ha seleccionado una fila de la tabla
            int fil = filasSelec[0];
            service.Evolucion evoAModificar = buscarEvolucionAModificar((Integer) tablaPrograma1.getValueAt(fil, 0),
                    (String) tablaPrograma1.getValueAt(fil, 1), (String) tablaPrograma1.getValueAt(fil, 2));
            EvolucionKine.idEvolucion = evoAModificar.getId();
            EvolucionKine.idFichaEvo = evoAModificar.getFichaClinica();
            evo.llenarDatosFormularioEvolucion(evoAModificar);
            evo.habilitarCamposFormulario(false);
            evo.ocultarCamposObligatorios(true);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.mensajeriaFormulario.setText("Debe seleccionar una evolución");
            this.mensajeriaFormulario.setForeground(Color.red);
        }
    }//GEN-LAST:event_verEvolucionActionPerformed

    private void actualizarTablaFiltro() {
        this.limpiarTablaEvoluciones();
        //listar Evoluciones y agregarlas a la Tabla
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        //Obtiene las fichas clinicas almacenadas en la base de datos
        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();

        for (int i = 0; i < evoluciones.size(); i++) {
            Date d = this.stringToDate(evoluciones.get(i).getFecha());
            if (evoluciones.get(i).isActivo() == true && evoluciones.get(i).getFichaClinica().equals(id)) {
                if (this.desdePro1.getDate().before(d) && this.hastaPro1.getDate().after(d) || this.esMismoDia(this.desdePro1.getDate(), d)
                        || this.esMismoDia(this.hastaPro1.getDate(), d)) {

                    int fila = this.tablaPrograma1.getRowCount();
                    DefaultTableModel modelo = (DefaultTableModel) this.tablaPrograma1.getModel();
                    modelo.addRow(new String[3]);
                    for (int col = 0; col < this.tablaPrograma1.getColumnCount(); col++) {
                        this.tablaPrograma1.setValueAt(evoluciones.get(i).getSesion(), fila, 0);
                        this.tablaPrograma1.setValueAt(evoluciones.get(i).getFecha(), fila, 1);
                        this.tablaPrograma1.setValueAt(evoluciones.get(i).getComentario(), fila, 2);
                    }
                }
            }
        }
    }

    public void limpiarTablaEvoluciones() {
        DefaultTableModel modelo = (DefaultTableModel) tablaPrograma1.getModel();
        int filas = tablaPrograma1.getRowCount();
        for (int i = 0; filas > i; i++) {
            modelo.removeRow(0);
        }
    }

    private static boolean esMismoDia(Date fecha1, Date fecha2) {
        if (fecha1 == null || fecha2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(fecha1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(fecha2);
        return isSameDay(cal1, cal2);
    }

    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarPrograma1;
    private javax.swing.JTextField apellidoMaterno1;
    private javax.swing.JTextField apellidoPaterno1;
    public javax.swing.JButton botonAgregar;
    public javax.swing.JButton botonCancelar;
    private com.toedter.calendar.JDateChooser cancelacion1;
    private com.toedter.calendar.JDateChooser desdePro1;
    private javax.swing.JTextField diagnostico1;
    private javax.swing.JTextArea evaluacion1;
    private javax.swing.JTextArea evaluacionFinal1;
    private javax.swing.JTextField examenes1;
    private com.toedter.calendar.JDateChooser fechaIngreso1;
    private com.toedter.calendar.JDateChooser hastaPro1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel42;
    private javax.swing.JLabel jLabel43;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel45;
    private javax.swing.JLabel jLabel46;
    private javax.swing.JLabel jLabel47;
    private javax.swing.JLabel jLabel48;
    private javax.swing.JLabel jLabel49;
    private javax.swing.JLabel jLabel50;
    private javax.swing.JLabel jLabel51;
    private javax.swing.JLabel jLabel52;
    private javax.swing.JLabel jLabel53;
    private javax.swing.JLabel jLabel54;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel16;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel19;
    private javax.swing.JScrollPane jScrollPane10;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JScrollPane jScrollPane9;
    public javax.swing.JLabel mensajeriaFormulario;
    private javax.swing.JButton modificarPrograma1;
    private javax.swing.JTextField nombres1;
    private javax.swing.JTextField patologias1;
    private javax.swing.JTextField prevision;
    private componentes.Rut rut;
    private javax.swing.JTable tablaPrograma1;
    private componentes.Telefono telefono;
    private javax.swing.JTextField tratamiento1;
    private javax.swing.JButton verEvolucion;
    // End of variables declaration//GEN-END:variables

    public service.FichaClinica buscarFicha(Long fichaKine) {
        service.FichaKineWSService service = new service.FichaKineWSService();
        service.FichaKineWS port = service.getFichaKineWSPort();

        java.util.List<service.FichaClinica> fichasKine = port.listarFichasClinicas();
        //buscar paciente por el rut
        for (int i = 0; i < fichasKine.size(); i++) {
            if (fichasKine.get(i).getId().equals(fichaKine)) {
                return fichasKine.get(i);
            }
        }
        return null;
    }

    public String capturarFecha(String parametro) {
        Calendar cal = Calendar.getInstance();
        String fecha = "dd-MM-yyyy";
        if (parametro.equals("fechaIngreso")) {
            if (this.fechaIngreso1.getDate() != null) {
                cal.setTime(this.fechaIngreso1.getDate());
                //Dia - mes - año
                fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                        + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                        + Integer.toString(cal.get(Calendar.YEAR));
            }
        } else {//obtiene la fecha de cancelacion de la ficha
            if (this.cancelacion1.getDate() != null) {
                cal.setTime(this.cancelacion1.getDate());
                //Dia - mes - año
                fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                        + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                        + Integer.toString(cal.get(Calendar.YEAR));
            }
        }
        return fecha;
    }

    public Date stringToDate(String strFecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd-MM-yyyy");
        Date fecha = null;
        try {
            fecha = formatoDelTexto.parse(strFecha);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return fecha;
    }

    /**
     * Método que Setea el formulario de una Ficha Clínica
     **/
    public void LimpiarFormularioFicha() {
        //datos personales
        this.rut.getRut().setText("");
        this.nombres1.setText("");
        this.apellidoPaterno1.setText("");
        this.apellidoMaterno1.setText("");
        this.prevision.setText("");
        this.telefono.getTelefono().setText("");
        //Datos Clinicos
        this.diagnostico1.setText("");
        this.examenes1.setText("");
        this.patologias1.setText("");
        this.evaluacion1.setText("");
        this.evaluacionFinal1.setText("");
        this.cancelacion1.setDate(null);
        this.tratamiento1.setText("");
        this.fechaIngreso1.setDate(null);
    }

    public void llenarCamposFichaClinica(service.Paciente pac, String accion) {
        this.rut.getRut().setText(pac.getRut());
        this.nombres1.setText(pac.getNombres());
        this.apellidoPaterno1.setText(pac.getApellidoPaterno());
        this.apellidoMaterno1.setText(pac.getApellidoMaterno());
        this.prevision.setText(pac.getPrevision());
        this.telefono.getTelefono().setText(pac.getTelefono());
        //bloquear los campos
        this.rut.getRut().setEditable(false);
        this.nombres1.setEditable(false);
        this.apellidoPaterno1.setEditable(false);
        this.apellidoMaterno1.setEditable(false);
        this.prevision.setEditable(false);
        this.telefono.getTelefono().setEditable(false);
        this.tablaPrograma1.setEnabled(false);
        this.agregarPrograma1.setEnabled(false);
        this.modificarPrograma1.setEnabled(false);
        this.verEvolucion.setEnabled(false);
        this.desdePro1.setEnabled(false);
        this.hastaPro1.setEnabled(false);

        if (accion.equals("agregar")) {
            this.botonAgregar.setText("Aceptar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));

        } else if (accion.equals("modificar")) {
            this.botonAgregar.setText("Guardar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        }

    }

    /**
     * Método que llena los datos de una ficha clinica en el formulario
     * @param fichaClinica de un paciente
     **/
    void llenarFormularioFichaKine(service.FichaClinica ficha) {
        //buscar información del paciente seleccionado
        service.Paciente pac = new service.Paciente();
        pac = buscarPaciente(ficha.getPaciente());

        //llena los datos personales del paciente
        this.rut.getRut().setText(ficha.getPaciente());
        this.nombres1.setText(pac.getNombres());
        this.apellidoPaterno1.setText(pac.getApellidoPaterno());
        this.apellidoMaterno1.setText(pac.getApellidoMaterno());
        this.prevision.setText(pac.getPrevision());
        this.telefono.getTelefono().setText(pac.getTelefono());
        //los Datos del Paciente no se pueden modificar en ninguna acción del módulo de ficha clínica
        this.rut.getRut().setEditable(false);
        this.nombres1.setEditable(false);
        this.apellidoPaterno1.setEditable(false);
        this.apellidoMaterno1.setEditable(false);
        this.prevision.setEditable(false);
        this.telefono.getTelefono().setEditable(false);
        //llena los datos clinicos del paciente
        this.diagnostico1.setText(ficha.getDiagnostico());
        this.examenes1.setText(ficha.getExamenes());
        this.patologias1.setText(ficha.getPatologia());
        this.evaluacion1.setText(ficha.getEvaluacionInicial());
        this.evaluacionFinal1.setText(ficha.getEvaluacionFinal());
        this.tratamiento1.setText(ficha.getTratamiento());
        if (!ficha.getFechaIngreso().equals("dd-MM-yyyy")) {
            this.fechaIngreso1.setDate(stringToDate(ficha.getFechaIngreso()));
        }
        if (!ficha.getCancelacion().equals("dd-MM-yyyy")) {
            this.cancelacion1.setDate(stringToDate(ficha.getCancelacion()));
        }
    }

    public void habilitarCamposFormulario(boolean habilitar) {
        this.diagnostico1.setEditable(habilitar);
        this.examenes1.setEditable(habilitar);
        this.patologias1.setEditable(habilitar);
        this.evaluacion1.setEditable(habilitar);
        this.tratamiento1.setEditable(habilitar);
        this.fechaIngreso1.setEnabled(habilitar);
        this.cancelacion1.setEnabled(habilitar);
        this.evaluacionFinal1.setEditable(habilitar);
        this.tablaPrograma1.setEnabled(habilitar);
        this.agregarPrograma1.setEnabled(habilitar);
        this.modificarPrograma1.setEnabled(habilitar);
        this.desdePro1.setEnabled(habilitar);
        this.hastaPro1.setEnabled(habilitar);
        this.verEvolucion.setEnabled(habilitar);
    }

    public service.Paciente buscarPaciente(String paciente) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();

        java.util.List<service.Paciente> pacientes = port.listarPacientes();
        //buscar paciente por el rut
        for (int i = 0; i < pacientes.size(); i++) {
            if (pacientes.get(i).getRut().equals(paciente)) {
                return pacientes.get(i);
            }
        }
        return null;
    }

    public void configurarBotones(String formulario) {
        if (formulario.equals("agregar")) {
            this.botonAgregar.setText("Agregar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else if (formulario.equals("modificar")) {
            this.botonAgregar.setText("Guardar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else {
            this.botonAgregar.setText("Exportar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/pdf.png")));
        }

    }

    public String eligeDireccionArchivo() {
        String dirArchivo = "";
        JFileChooser jFileChooser1 = new JFileChooser();
        jFileChooser1.setDialogTitle("Guardar archivo:");
        jFileChooser1.setVisible(true);

        int r = jFileChooser1.showSaveDialog(null);
        if (r == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            dirArchivo = String.valueOf(file);
        }
        dirArchivo = dirArchivo.replace('\\', '/') + ".pdf";
        return dirArchivo;

    }

    private void imprimirFichaClinica(service.FichaClinica ficha) throws FileNotFoundException, DocumentException {
        service.Paciente paciente = buscarPaciente(ficha.getPaciente());

        Document documento = new Document();
        String dirArchivo = eligeDireccionArchivo();

        FileOutputStream ficheroPdf = new FileOutputStream(dirArchivo);// Se crea el OutputStream para el fichero donde queremos dejar el pdf.
        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
        documento.open();// Se abre el documento.

        Paragraph titulo = new Paragraph("FICHA CLINICA KINESIOLOGÍA");
        titulo.setAlignment(Element.ALIGN_CENTER);
        titulo.setSpacingAfter(20);
        documento.add(titulo);

        Paragraph datosPersonales = new Paragraph("Datos Personales");
        datosPersonales.setAlignment(Element.ALIGN_LEFT);
        datosPersonales.setSpacingAfter(20);
        documento.add(datosPersonales);

        PdfPTable table = new PdfPTable(2);
        table.addCell("Rut: ");
        table.addCell(paciente.getRut());
        table.addCell("Nombres: ");
        table.addCell(paciente.getNombres());
        table.addCell("Apellido Paterno:");
        table.addCell(paciente.getApellidoPaterno());
        table.addCell("Apellido Materno: ");
        table.addCell(paciente.getApellidoMaterno());
        documento.add(table);

        Paragraph datosClinicos = new Paragraph("Datos Clínicos");
        datosClinicos.setAlignment(Element.ALIGN_LEFT);
        datosClinicos.setSpacingAfter(20);
        documento.add(datosClinicos);

        PdfPTable tabla = new PdfPTable(2);
        tabla.addCell("Diagnóstico: ");
        tabla.addCell(ficha.getDiagnostico());
        tabla.addCell("Exámenes: ");
        tabla.addCell(ficha.getExamenes());
        tabla.addCell("Patologías: ");
        tabla.addCell(ficha.getPatologia());
        tabla.addCell("Tratamiento: ");
        tabla.addCell(ficha.getTratamiento());
        tabla.addCell("Evaluación Inicial: ");
        tabla.addCell(ficha.getEvaluacionInicial());
        tabla.addCell("Fecha Ingreso: ");
        tabla.addCell(ficha.getFechaIngreso());
        tabla.addCell("Cancelación: ");
        tabla.addCell(ficha.getCancelacion());
        tabla.addCell("Profesional: ");
        tabla.addCell(ficha.getProfesional());
        tabla.addCell("Evaluación Final: ");
        tabla.addCell(ficha.getEvaluacionFinal());
        documento.add(tabla);

        documento.close();
        abrirArchivo(dirArchivo);
    }

    public void abrirArchivo(String direccion) {
        //Abre el documento pdf
        try {
            File file = new File(direccion);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean estaDuplicada(String paciente, String profesional) {
        java.util.List<service.FichaClinica> fichas = listarFichas();

        for (int i = 0; i < fichas.size(); i++) {
            if (fichas.get(i).getPaciente().equals(paciente) && fichas.get(i).getProfesional().equals(profesional)) {
                return true;
            }
        }
        return false;
    }

    private static java.util.List<service.FichaClinica> listarFichas() {
        service.FichaKineWSService service = new service.FichaKineWSService();
        service.FichaKineWS port = service.getFichaKineWSPort();
        return port.listarFichasClinicas();
    }

    private boolean llenoDatosObligatorios() {
        if (this.diagnostico1.getText().equals("") || this.tratamiento1.getText().equals("")
                || this.fechaIngreso1.getDate() == null) {
            return false;
        }
        return true;
    }

    public void agregarDatoTablaEvolucion(int sesion, String fechaEvolucion, String comentario) {
        int fila = this.tablaPrograma1.getRowCount();
        DefaultTableModel modelo = (DefaultTableModel) this.tablaPrograma1.getModel();
        modelo.addRow(new String[3]);

        //coloca los datos de la ficha recientemente agregada
        for (int col = 0; col < this.tablaPrograma1.getColumnCount(); col++) {
            this.tablaPrograma1.setValueAt(sesion, fila, 0);
            this.tablaPrograma1.setValueAt(fechaEvolucion, fila, 1);
            this.tablaPrograma1.setValueAt(comentario, fila, 2);
        }
    }

    public void cambiarMensajeria(String eti) {
        p.etiquetaMensajeria.setText(eti);
    }

    public void modificarDatoTabla(int s, String fecha, String comentario) {
        int fila = this.tablaPrograma1.getSelectedRow();
        this.tablaPrograma1.setValueAt(s, fila, 0);
        this.tablaPrograma1.setValueAt(fecha, fila, 1);
        this.tablaPrograma1.setValueAt(comentario, fila, 2);
    }

    public service.Evolucion buscarEvolucionAModificar(int sesion, String fecha, String comentario) {
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();

        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        //buscar la ficha clinica por el id de la ficha
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).getSesion() == sesion && evoluciones.get(i).getFecha().equals(fecha)
                    && evoluciones.get(i).getComentario().equals(comentario)) {
                return evoluciones.get(i);
            }
        }
        return null;
    }

    public void llenardatosEvoluciones(Long id) {
        //listar Evoluciones y agregarlas a la Tabla
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        //Obtiene las fichas clinicas almacenadas en la base de datos
        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).isActivo() == true && evoluciones.get(i).getFichaClinica().equals(id)) {

                int fila = this.tablaPrograma1.getRowCount();
                DefaultTableModel modelo = (DefaultTableModel) this.tablaPrograma1.getModel();
                modelo.addRow(new String[3]);

                for (int col = 0; col < this.tablaPrograma1.getColumnCount(); col++) {
                    this.tablaPrograma1.setValueAt(evoluciones.get(i).getSesion(), fila, 0);
                    this.tablaPrograma1.setValueAt(evoluciones.get(i).getFecha(), fila, 1);
                    this.tablaPrograma1.setValueAt(evoluciones.get(i).getComentario(), fila, 2);
                }
            }
        }
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }
    
    public void ocultarAsteriscosFormulario(boolean ocultar){
        if(ocultar==true){
            this.jLabel6.setText("");
            this.jLabel9.setText("");
            this.jLabel10.setText("");
            this.jLabel12.setText("");
            this.mensajeriaFormulario.setText("");
        }else{
            this.jLabel6.setText("*");
            this.jLabel9.setText("*");
            this.jLabel10.setText("*");
            this.jLabel12.setText("*Datos obligatorios");
            this.mensajeriaFormulario.setText("Área Mensajería");
        }
    }
     void habilitarCamposEvolucion(boolean b) {
        this.verEvolucion.setEnabled(b);
        this.tablaPrograma1.setEnabled(b);
        this.desdePro1.setEnabled(b);
        this.hastaPro1.setEnabled(b);
    }
}
